package cn.xspace.wnx.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.PageBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;

import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import com.xspace.android.xafcommon.util.PageUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.WnxOrgMessageListAdapter;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.db.NoticeDao;
import cn.xspace.wnx.db.WNXDBManager;
import cn.xspace.wnx.entity.WNXBean;
import cn.xspace.wnx.util.Navigator;
import com.xspace.android.xafcommon.util.T;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 微农信的消息列表界面,带图文,点开之后打开WebView
 * Created by Administrator on 2016/11/12.
 */
public class WnxOrgMessageListActivity extends BaseActivity {

    private static final String TAG = WnxOrgMessageListActivity.class.getSimpleName();

    private ArrayList<WNXBean> dataList;
    public static String WNXBEAN = "WNXBean";
    protected ListView listView;
    protected TitleBar mTitle;
    protected SwipeRefreshLayout swipeRefreshLayout;
    private WNXBean mWnxBean;
    protected PageBean mPageBean = new PageBean();
    private int pageIndex = 0;
    private WnxOrgMessageListAdapter wnxOrgMessageListAdapter;
    private String userMobile;
    private String userId = "";
    private String senderId = ""; //机构Id
    private String senderName = ""; //机构名字
    //    private String searchId = ""; //要查找某个人的消息
//    private String searchPhone = ""; //要查找某个人的消息
    private boolean lookHistory; //是否是点击查看历史消息进来的

    public static boolean isAlive;

    public int msgType = MsgType.NOTICE.toNumber();

    private boolean firstIn = true;
    private boolean haveMoreDataLocal = false;
    private boolean isRefresh = false;
    private boolean isLocalDataExsit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(mContext);
        isAlive = true;
        setWnxRead();
    }

    @Override
    protected void onDestroy() {
        isAlive = false;
        super.onDestroy();
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        mWnxBean = (WNXBean) getIntent().getSerializableExtra(WNXBEAN);

        if (mWnxBean == null) {
            Bundle mBundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
            senderId = mBundle.getString(BldNavigation.SENDER_ID);
            senderName = mBundle.getString(BldNavigation.SENDER_NAME);
            lookHistory = mBundle.getBoolean(BldNavigation.LOOK_HISTORY);
//            searchId = mBundle.getString(RequestConstant.KEY_SEARCH_ID);
//            searchPhone = mBundle.getString(RequestConstant.KEY_SEARCH_PHONE);
            msgType = mBundle.getInt(BldNavigation.CHAT_TYPE, MsgType.NOTICE.toNumber());
        } else {
            senderId = mWnxBean.msg_sender_id;
            senderName = mWnxBean.msg_sender_name;
            msgType = mWnxBean.msg_type;
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_wnx_orglist);

    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.chat_swipe_layout);
        listView = (ListView) findViewById(R.id.list);
        mTitle = (TitleBar) findViewById(R.id.title_bar);
    }

    @Override
    protected void initData() {
        super.initData();
        dataList = new ArrayList<>();
        wnxOrgMessageListAdapter = new WnxOrgMessageListAdapter(mContext, dataList, listView);
        listView.setAdapter(wnxOrgMessageListAdapter);
        getData();

        //将某一部门是微农信推送信息设为已读
        NoticeDao.getInstance().getData().updateWnxOrgReadStatus(senderId)
                .subscribeOn(Schedulers.io())
                .subscribe();
    }


    private void getData() {
        LogUtil.d(TAG, "wubaojie>>>getData: ");
        if (lookHistory) { //如果是查看历史消息,则需要访问网络获取
            getDataFromNet();
        } else {
            registerSubscription(NoticeDao.getInstance().getData().getWnxListBySenderid(senderId, pageIndex)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<ArrayList<WNXBean>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(ArrayList<WNXBean> wnxBeen) {
                            if (wnxBeen.size() == 0 && isRefresh) {
                                //本地没有请求网络的数据
                                getDataFromNet();
                            } else {
                                isLocalDataExsit = true;
                                LogUtil.d(wnxBeen.toString());
                                swipeRefreshLayout.setRefreshing(false);
                                if (wnxBeen.size() < PageUtil.PAGE_SIZE && !firstIn) {
                                    T.showShort(mContext, ResourceUtils.getString(R.string.no_more_messages));
                                }
                                firstIn = false;
                                int oldPostion = wnxBeen.size();
                                dataList.addAll(0, wnxBeen);
                                LogUtil.d(TAG, "wubaojie>>>onNext: datalist:" + dataList.toString());
                                wnxOrgMessageListAdapter.refreshSeekTo(oldPostion - 1);
                            }

                        }
                    }));
        }
    }

    private void removeBeanByMsgId(String msgId) {
        for (WNXBean wnxBean : dataList) {
            if (msgId.equals(wnxBean.msg_id)) {
                dataList.remove(wnxBean);
                return;
            }
        }
    }

    private void getDataFromNet() {
        if (firstIn) {
            showWaitDialog();
        }
//        if (TextUtils.isEmpty(searchId) && TextUtils.isEmpty(searchPhone)) {
        userId = MyInfoUtil.getMyUserid(mContext);
        userMobile = MyInfoUtil.getMyMobile(mContext);
//        } else {
//            userId = searchId;
//            userMobile = searchPhone;
//        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(RequestConstant.KEY_USER_ID, userId);
        dataMap.put(RequestConstant.KEY_USER_MOBILE, userMobile);
        dataMap.put(RequestConstant.KEY_DEP_ID, senderId);
        if (dataList.size() > 0 && !TextUtils.isEmpty(dataList.get(0).msg_id)) {
            mPageBean.page_index = dataList.get(0).page_index;
        }
        if (dataList.size() == 0) {
            mPageBean.page_turn = PageUtil.PAGE_DOWN;
        } else {
            mPageBean.page_turn = PageUtil.PAGE_UP;
        }
        if (TextUtils.isEmpty(mPageBean.page_index)) {
            mPageBean.page_turn = PageUtil.PAGE_DOWN;
            mPageBean.page_index = "0";
        }
        mPageBean.page_size = PageUtil.PAGE_SIZE;
        dataMap.put(RequestConstant.KEY_PG, mPageBean);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.QUERY_PUSH_MSG, dataMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, ArrayList<WNXBean>>() {

                    @Override
                    public ArrayList<WNXBean> call(BaseReturnBean baseReturnBean) {
                        LogUtil.d(TAG, "wubaojie>>>" + "call: baseReturnBean.data :" + baseReturnBean.data);
                        ArrayList<WNXBean> beanList = new ArrayList<>();
                        try {
                            JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject json = (JSONObject) jsonArray.get(i);
                                WNXBean bean = new WNXBean();
                                bean.msg_title = json.optString("msg_title");
                                bean.msg_kind = json.optString("msg_type");
                                if (TextUtils.equals(bean.msg_kind, "通知公告")) {
                                    continue;// TODO 如果通知公告不要就再做处理
                                }
                                JSONObject jsonObject = new JSONObject(json.optString("msg_content"));
                                bean.content = jsonObject.optJSONArray("newssnap").toString();
                                if (mWnxBean != null) {
                                    bean.msg_logo = mWnxBean.msg_logo;
                                }
//                                bean.msg_logo = json.optString("msg_logo");
                                String send_time = json.optString("msg_sendtime");
                                bean.msg_send_time = DateUtils.StringToString(null, send_time);
                                bean.page_index = json.optString("page_index");
                                bean.msg_id = json.optString("task_id");
                                removeBeanByMsgId(bean.msg_id);
                                bean.msg_unread_flag = 1;
                                bean.isHistory = true;
                                //发送人，发送人Id
                                bean.msg_sender_id = senderId;
                                bean.msg_sender_name = senderName;
                                beanList.add(bean);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        LogUtil.d(TAG, "wubaojie>>>" + "call: bean :" + beanList.toString());
                        return beanList;
                    }
                })
                .doOnNext(new Action1<ArrayList<WNXBean>>() {
                    @Override
                    public void call(ArrayList<WNXBean> wnxBeen) {
                        Collections.reverse(wnxBeen);
                    }
                })
                .doOnNext(new Action1<ArrayList<WNXBean>>() {
                    @Override
                    public void call(ArrayList<WNXBean> wnxBeenList) {
                        if (!lookHistory) {
                            //先想本地的空数据删除
                            WNXDBManager.getInstance().deleleBlankWnx(senderId);
                            //保存到本地
                            for (WNXBean wnxBean : wnxBeenList) {
                                WNXDBManager.getInstance().insertWnxNotice(wnxBean);
                            }
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<WNXBean>>() {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(List<WNXBean> wnxBeen) {
                        hideWaitDialog();
                        swipeRefreshLayout.setRefreshing(false);
                        LogUtil.d(TAG, "wubaojie>>>onNext: wnxBean.size:" + wnxBeen.size());
                        LogUtil.d(wnxBeen.toString());
                        if (wnxBeen.size() < PageUtil.PAGE_SIZE && !firstIn) {
                            T.showShort(mContext, ResourceUtils.getString(R.string.no_more_messages));
                        }
                        firstIn = false;
                        int oldPostion = wnxBeen.size();
                        dataList.addAll(0, wnxBeen);
                        wnxOrgMessageListAdapter.refreshSeekTo(oldPostion - 1);
                    }
                }));

    }


    @Override
    protected void initEvent() {
        super.initEvent();
        mTitle.setTitle(senderName);
        if (lookHistory) {
            mTitle.setRightLayoutVisibility(View.GONE);
        } else {
            mTitle.setRightLayoutVisibility(View.VISIBLE);
            mTitle.setRightLayoutClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Navigator.startOrgInfoActivity(mContext, senderId);
                }
            });
        }
        mTitle.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageIndex++;
                LogUtil.d(TAG, "wubaojie>>>onRefresh: ");
                isRefresh = true;
                getData();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    private void setWnxRead() {
        registerSubscription(MessageRecordDao.getInstance().getiMessageData().updateUnreadStatus("", MsgType.WNX_MSG.toNumber())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe());
    }


    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        super.onEventMainThread(inParam);
        if (EventBusConstant.XMPP_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            Object obj = inParam.get(EventBusConstant.XMPP_PUSH_BEAN);
            if (obj instanceof WNXBean) {
                WNXBean wnxBean = (WNXBean) obj;
                if (senderId.equals(wnxBean.msg_sender_id) && msgType == wnxBean.msg_type) {
                    dataList.add(wnxBean);
                    refreshSeekTo(listView.getFirstVisiblePosition());
                }
            }
        } else if (EventBusConstant.CLEAR_WNX_OR_NOTICE.equals(inParam.get(EventBusConstant.TYPE))) {
            LogUtil.d(TAG, "wubaojie>>>onEventMainThread: 刷新界面");
            String logo = "";
            if (inParam.get(EventBusConstant.ACTION_VALUE) != null) {
                logo = inParam.get(EventBusConstant.ACTION_VALUE).toString();
            }
            WNXBean wnxBean = new WNXBean();
            wnxBean.msg_type = MsgType.WNX_MSG.toNumber();
            wnxBean.msg_sender_id = senderId;
            wnxBean.msg_sender_name = senderName;
            LogUtil.d(" dataList " + dataList.toString());
//            if (dataList != null && dataList.size() > 0) {
//                wnxBean.msg_send_time = dataList.get(dataList.size() - 1).msg_send_time;
//            }
            wnxBean.msg_logo = logo;
            wnxBean.bean_type = 1;
            wnxBean.msg_unread_flag = 1;
            WNXDBManager.getInstance().insertWnxNotice(wnxBean);

            if (dataList != null) {
                dataList.clear();
                refresh();
            }
        }
    }

    /**
     * 判断该界面是否还存在
     *
     * @return
     */
    public static boolean isActivityAlive() {
        return isAlive;
    }

    /**
     * refresh
     */
    public void refresh() {
        if (wnxOrgMessageListAdapter != null) {
            wnxOrgMessageListAdapter.refresh();
        }
    }

    /**
     * refresh and jump to the last
     */
    public void refreshSelectLast() {
        if (wnxOrgMessageListAdapter != null) {
//            wnxOrgMessageListAdapter.setmDataList(mDataList);
            wnxOrgMessageListAdapter.refreshSelectLast();
        }
    }

    /**
     * refresh and jump to the position
     *
     * @param position
     */
    public void refreshSeekTo(int position) {
        if (wnxOrgMessageListAdapter != null) {
            wnxOrgMessageListAdapter.refreshSeekTo(position);
        }
    }
}
